/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.redeemcode.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.tickettype.entity.TicketType;
import com.jeeplus.modules.tickettype.service.TicketTypeService;
import com.jeeplus.modules.topic.entity.Topic;
import com.jeeplus.modules.topic.service.TopicService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.redeemcode.entity.RedeemCode;
import com.jeeplus.modules.redeemcode.service.RedeemCodeService;

/**
 * 兑换码Controller
 * @author zhych
 * @version 2021-08-23
 */
@RestController
@RequestMapping(value = "/redeemcode/redeemCode")
public class RedeemCodeController extends BaseController {

	@Autowired
	private RedeemCodeService redeemCodeService;

	@Autowired
	private TopicService topicService;

	@Autowired
	private TicketTypeService ticketTypeService;

	@ModelAttribute
	public RedeemCode get(@RequestParam(required=false) String id) {
		RedeemCode entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = redeemCodeService.get(id);
		}
		if (entity == null){
			entity = new RedeemCode();
		}
		return entity;
	}

	/**
	 * 兑换码列表数据
	 */
	@RequiresPermissions("redeemcode:redeemCode:list")
	@GetMapping("list")
	public AjaxJson list(RedeemCode redeemCode, HttpServletRequest request, HttpServletResponse response) {
		Page<RedeemCode> page = redeemCodeService.findPage(new Page<>(request, response), redeemCode);
		for (RedeemCode code : page.getList()) {
			TicketType ticketType = ticketTypeService.get(code.getTicketTypeId());
			code.setTicketTypeId(ticketType.getTitle());
		}
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 根据Id获取兑换码数据
	 */
	@RequiresPermissions(value={"redeemcode:redeemCode:view","redeemcode:redeemCode:add","redeemcode:redeemCode:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(RedeemCode redeemCode) {
		return AjaxJson.success().put("redeemCode", redeemCode);
	}

	/**
	 * 保存兑换码
	 */
	@RequiresPermissions(value={"redeemcode:redeemCode:add","redeemcode:redeemCode:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(RedeemCode redeemCode, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		// 添加查询该兑换码是否存在
		// 主题名称添加
		Topic topic = topicService.get(redeemCode.getTopic());
		redeemCode.setTopicTitle(topic.getTitle());
		RedeemCode code = redeemCodeService.findUniqueByProperty("code", redeemCode.getCode());
		if (StringUtils.isBlank(redeemCode.getId()) && !Objects.isNull(code)) {
			return AjaxJson.error("该兑换码已存在");
		}
		if (StringUtils.isNotBlank(redeemCode.getId()) && !Objects.isNull(code) && !redeemCode.getId().equals(code.getId())) {
			return AjaxJson.error("该兑换码已存在");
		}
		String errMsg = beanValidator(redeemCode);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		redeemCodeService.save(redeemCode);//保存
		return AjaxJson.success("保存兑换码成功");
	}


	/**
	 * 批量删除兑换码
	 */
	@RequiresPermissions("redeemcode:redeemCode:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			redeemCodeService.deleteByLogic(new RedeemCode(id));
		}
		return AjaxJson.success("删除兑换码成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("redeemcode:redeemCode:export")
    @GetMapping("export")
    public AjaxJson exportFile(RedeemCode redeemCode, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "兑换码"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<RedeemCode> page = redeemCodeService.findPage(new Page<RedeemCode>(request, response, -1), redeemCode);
			for (RedeemCode code : page.getList()) {
				if (StringUtils.isNotBlank(code.getTicketTypeId())) {
					TicketType ticketType = ticketTypeService.get(code.getTicketTypeId());
					code.setTicketTypeId(ticketType.getTitle());
				}
			}
    		new ExportExcel("兑换码", RedeemCode.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出兑换码记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("redeemcode:redeemCode:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<RedeemCode> list = ei.getDataList(RedeemCode.class);
			for (RedeemCode redeemCode : list){
				try{
					redeemCodeService.save(redeemCode);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条兑换码记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条兑换码记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入兑换码失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入兑换码数据模板
	 */
	@RequiresPermissions("redeemcode:redeemCode:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "兑换码数据导入模板.xlsx";
    		List<RedeemCode> list = Lists.newArrayList();
    		new ExportExcel("兑换码数据", RedeemCode.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }

    @RequestMapping("addLoopCode")
	public AjaxJson createLoopCode(RedeemCode redeemCode) {
		if (redeemCode.getCount() <= 0) {
			return AjaxJson.error("数量填写错误，请修改");
		}
		Topic topic = topicService.get(redeemCode.getTopic());
		if (Objects.isNull(topic)) {
			return AjaxJson.error("该主题不存在");
		}
		redeemCodeService.addLoopCode(redeemCode);
		return AjaxJson.success("创建成功");
	}
}